package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.util.Convert;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class BpmnInfoServiceImpl implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private RepositoryService repositoryService;

    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectForList(qo));
    }


    @Override
    public void save(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public BpmnInfo get(Long id) {
        return bpmnInfoMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.updateByPrimaryKey(bpmnInfo);

    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            bpmnInfoMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<BpmnInfo> list() {
        return bpmnInfoMapper.selectAll();
    }

    @Override
    public void deploy(String bpmnInfoPath, String bpmnType, String info) throws IOException {
        //获取流程定义文件
        File file = new File(SystemConfig.getProfile(),bpmnInfoPath);
        //将流程部署到Activiti7中
        FileInputStream inputStream = new FileInputStream(file);
        Deployment deployment = repositoryService.createDeployment()
                .addInputStream(bpmnInfoPath, inputStream)
                .deploy();
        //封装bpmnInfo数据
        BpmnInfo bpmnInfo = new BpmnInfo();
        bpmnInfo.setDeploymentId(deployment.getId());//部署id
        bpmnInfo.setDeployTime(new Date());//部署时间
        bpmnInfo.setBpmnType(bpmnType);//流程类型
        bpmnInfo.setInfo(info);//备注信息
        //获取流程定义对象
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deployment.getId())
                .singleResult();
        //获取流程定义的资源
        bpmnInfo.setActProcessId(definition.getId());//流程定义id
        bpmnInfo.setBpmnName(definition.getName());//流程名称
        bpmnInfo.setActProcessKey(definition.getKey());//key
        //保存数据
        bpmnInfoMapper.insert(bpmnInfo);
        inputStream.close();
    }

    @Override
    public InputStream getResoucceByType(String deploymentId, String type) {
        //获取流程定义对象
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploymentId).singleResult();
        //判断类型
        if ("xml".equalsIgnoreCase(type)) {
            return repositoryService.getResourceAsStream(deploymentId,definition.getResourceName());
        } else if ("png".equalsIgnoreCase(type)) {
            BpmnModel model = repositoryService.getBpmnModel(definition.getId());
            DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
            //generateDiagram(流程模型,需要高亮的节点,需要高亮的线条,后面三个参数都表示是字体)
            InputStream inputStream = generator.generateDiagram(model, Collections.EMPTY_LIST, Collections.EMPTY_LIST,"宋体","宋体","宋体");
            return inputStream;
        }
        return null;
    }

    @Override
    public void delete(Long id) {
        //1.先根据id查询bpmnInfo对象
        BpmnInfo bpmnInfo = get(id);
        //2.删除bpmnInfo对象
        bpmnInfoMapper.deleteByPrimaryKey(id);
        //3.删除Activiti流程定义的信息(级联删除)
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(bpmnInfo.getDeploymentId())
                .latestVersion()
                .singleResult();
        repositoryService.deleteDeployment(bpmnInfo.getDeploymentId(),true);
        //4.获取到服务器上的文件,把文件删除掉
        String name = definition.getResourceName();
        File file = new File(SystemConfig.getProfile(),name);
        if (file.exists()) {
            //清除缓存
            //System.gc();
            file.delete();
        }
    }

    @Override
    public BpmnInfo queryByType(String type) {
        return bpmnInfoMapper.getByBpmnType(type);
    }
}
